package com.zwcl.glass.goods.service.impl;

import com.zwcl.common.component.upload.cloud.OSSFactory;
import com.zwcl.common.core.excel.AbstractImportService;
import com.zwcl.glass.goods.dto.GoodsImportDto;
import com.zwcl.glass.goods.entity.Brand;
import com.zwcl.glass.goods.entity.Categories;
import com.zwcl.glass.goods.entity.GoodsImages;
import com.zwcl.glass.goods.entity.GoodsSpu;
import com.zwcl.glass.goods.service.BrandService;
import com.zwcl.glass.goods.service.CategoriesService;
import com.zwcl.glass.goods.service.GoodsImagesService;
import com.zwcl.glass.goods.service.GoodsSpuService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;

import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
import java.math.BigDecimal;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.atomic.AtomicReference;
import java.util.function.Consumer;
import java.util.stream.Collectors;

/**
 * 录题
 */
@Service
@Slf4j
public class GoodsImportServiceImpl extends AbstractImportService<GoodsImportDto , GoodsImportDto> {

    @Autowired
    private BrandService brandService;

    @Autowired
    private CategoriesService categoriesService;

    @Autowired
    private GoodsImagesService goodsImagesService;

    @Autowired
    private GoodsSpuService goodsSpuService;

    @Autowired
    private OSSFactory ossFactory;

    private final static String loaclBasePath = "C:\\Users\\Administrator\\Desktop\\镜片录入";

    /**
     * 保存数据
     * @param param
     * @return
     */
    @Override
    protected Consumer<List<GoodsImportDto>> saveData(GoodsImportDto param) {
        AtomicReference<Integer> count= new AtomicReference<>(0);
        Map<Integer,String> imgFailMap = new HashMap<>();
        return list -> {
            List<GoodsSpu> goodsSpus = list.stream().map(goodsImportDto -> {
                try {
                    //1. 品牌和类别处理
                    Integer brandId = saveBrand(goodsImportDto.getBrandName());
                    //2. 商品处理
                    Integer cateId = saveCate(goodsImportDto.getCateName());
                    //2. 商品图片处理
                    GoodsSpu goodsSpu = new GoodsSpu();
                    goodsSpu.setBrandId(brandId);
                    goodsSpu.setCateId(cateId);
                    goodsSpu.setGoodsName(goodsImportDto.getGoodsName());
                    goodsSpu.setSummary(goodsImportDto.getSummary());
                    goodsSpu.setLowPrice(new BigDecimal(goodsImportDto.getPrice()));
                    goodsSpu.setHightPrice(new BigDecimal(goodsImportDto.getPrice()));
                    goodsSpu.setTags("|"+goodsImportDto.getTags().replace("，","|")+"|");
                    goodsSpu.setJdPrice(new BigDecimal(goodsImportDto.getJdPrice()));
                    goodsSpu.setTbPrice(new BigDecimal(goodsImportDto.getTbPrice()));
                    goodsSpu.setOuterSkuUrl(goodsImportDto.getOuterSkuUrl());
                    goodsSpuService.save(goodsSpu);
                    log.info("excel数据：{}", goodsImportDto);
                    //上传图片并且保存
                    Integer imgId= saveImgs(goodsImportDto.getGoodsImgs(),goodsSpu.getId());
                    if(null==imgId){
                        imgFailMap.put(goodsSpu.getId(),goodsImportDto.getGoodsImgs());
                    }else {
                        count.getAndSet(count.get() + 1);
                    }
                    return goodsSpu;
                }catch (Exception ex){
                    log.error("导入第{}条数据错误：{}",goodsImportDto.getGoodsNo(),ex);
                    return null;
                }
            }).collect(Collectors.toList());

            log.info("一共导入成功{}条数据",count);
            log.info("失败的图片：{}",imgFailMap);
        };
    }

    private Integer saveBrand(String brandName){
        Brand brand = brandService.getBrandByName(brandName);
        if(null == brand){
            brand =new Brand();
            brand.setBrandName(brandName);
            brand.setSort(99);
            brandService.save(brand);
        }
        return brand.getId();
    }

    private Integer saveCate(String cateName){
        Categories categories = categoriesService.getCategoriesByName(cateName);
        if(null == categories){
            categories =new Categories();
            categories.setCateName(cateName);
            categories.setCateCode("");
            categoriesService.save(categories);
        }
        return categories.getId();
    }

    private Integer saveImgs(String localPath,Integer spuId){
        try {
            localPath.replace("/","\\");
            String imgPath = loaclBasePath+"\\"+localPath;
            String suffix=".jpg";
            if(imgPath.lastIndexOf(".")>=0) {
                suffix = imgPath.substring(imgPath.lastIndexOf("."));
            }else {
                imgPath=imgPath+suffix;
            }
            String url = ossFactory.build().uploadSuffix(new FileInputStream(new File(imgPath)),suffix,null);
            GoodsImages goodsImages =new GoodsImages();
            goodsImages.setIsMaster(true);
            goodsImages.setLink(url);
            goodsImages.setSpuId(spuId);
            goodsImagesService.save(goodsImages);
            return goodsImages.getId();
        }catch (Exception e){
            log.error("SpuId{},图片上传失败，原因：{}",spuId,e);
            return null;
        }
    }

    //异步执行
    @Async
    public void importData(InputStream inputStream) {
        readExcel(inputStream, GoodsImportDto.class, null);
    }
}
